package cn.minimelon.bittermelon.web;

import cn.minimelon.bittermelon.bean.LoginUser;
import cn.minimelon.bittermelon.properties.RuntimeProperties;
import cn.minimelon.bittermelon.utils.Melon;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.util.PathAnalyzer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登录过滤器
 *
 * @author hiro
 */
@Component(index = 1)
public class LoginFilter implements Filter {
    private final static Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Inject("${melon.runtime}")
    RuntimeProperties runtimeProperties;

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        String token = ctx.header(runtimeProperties.getTokenName());
        logger.info(ctx.uri().getPath());
        if (!matchesNotFilter(ctx.uri().getPath()) && Melon.isEmpty(token)) {
            ctx.status(506);
            ctx.output("请重新登录...");
            logger.error(ctx.uri().getPath() + " 未登录不能访问……");
        } else {
            ctx.attrSet(Melon.LOGIN_USER_SESSION, new LoginUser("1", "admin", "超级管理员"));
            chain.doFilter(ctx);
        }
    }

    private boolean matchesNotFilter(String path) {
        return PathAnalyzer.get("/common/**").matches(path);
    }
}
